import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:get/get_state_manager/get_state_manager.dart';
import 'package:gt_flutter_admin/widgets/image_picker/image_picker_controller.dart';

class ImagePicker extends GetView<ImagePickerController> {
  ImagePicker(
    this.onTap, {
    Key? key,
    this.imageUrl,
    this.width = 45.0,
    this.height = 45.0,
  }) : super(key: key);

  final ValueChanged<String> onTap;
  final String? imageUrl;
  final double width;
  final double height;

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      child: Container(
        decoration: BoxDecoration(
          color: Colors.grey[300],
          border: Border.all(width: 0.5, style: BorderStyle.solid),
          borderRadius: BorderRadius.all(Radius.circular(4.0)),
        ),
        child: _buildImageWidget(),
        width: width,
        height: height,
      ),
      onTap: () async {
        // 上传本地文件
        String? imageUrl = await controller.onUploadImageFile();
        if (imageUrl != null) {
          onTap(imageUrl);
        }
      },
    );
  }

  // 构建图片
  Widget _buildImageWidget() {
    if (imageUrl != null) {
      return CachedNetworkImage(
        imageUrl: imageUrl!,
        fit: BoxFit.cover,
        width: width,
        height: height,
      );
    } else {
      return controller.obx((state) {
        return Image.file(
          controller.imageFile!,
          fit: BoxFit.cover,
          width: width,
          height: height,
        );
      }, onLoading: Icon(Icons.add_photo_alternate));
    }
  }
}
